import React, { Component } from 'react';

import { Confirm, Tip } from '../index/content'
import { getParams } from '../Tool'

import { Finish, Header, List, Test, Time, Title } from './content'

import './index.less'

import { home } from '@/api';

export default class Main extends Component {
    constructor(props) {
        super(props);
        this.params = getParams();
        if (this.params.subject_id === undefined) {
            WPT.showPage('/e403');
            return;
        }
        this.state = {
            pageNum: 0,
            submit: false,
            btnArr: null,
            answerArr: null,
            showConfirm: false,
            confirmInfo: '',
            confirmCallback: null,
            confirmMsg: null,
            typeList: null,
            questions: null,
            showTip: false,
            tipInfo: ''
        };
        this.total = 0;
        this.pageArr = ['首页'];
        this.start_time = this.getCurrentTime();
    }

    // eslint-disable-next-line react/sort-comp
    getData = () => {
        {
            // const typeList = {};
            // const questions = {};
            // const btnArr = {};
            // const answerArr = {};
            // const data = [
            //     {
            //         question_type: '单选题',
            //         score: 10,
            //         question_list: new Array(1).fill({
            //             question_id: '1',
            //             content: 'afasdf',
            //             options: [
            //                 {
            //                     option_id: 'A',
            //                     options_content: '1'
            //                 },
            //                 {
            //                     option_id: 'B',
            //                     options_content: '2'
            //                 },
            //                 {
            //                     option_id: 'C',
            //                     options_content: '3'
            //                 },
            //                 {
            //                     option_id: 'd',
            //                     options_content: '4'
            //                 }
            //             ]
            //         })
            //     },
            //     {
            //         question_type: '多选题',
            //         score: 10,
            //         question_list: new Array(1).fill({
            //             question_id: '1',
            //             content: 'afasdf',
            //             options: [
            //                 {
            //                     option_id: 'A',
            //                     options_content: '1'
            //                 },
            //                 {
            //                     option_id: 'B',
            //                     options_content: '2'
            //                 },
            //                 {
            //                     option_id: 'C',
            //                     options_content: '3'
            //                 },
            //                 {
            //                     option_id: 'd',
            //                     options_content: '4'
            //                 }
            //             ]
            //         })
            //     },
            //     {
            //         question_type: '判断题',
            //         score: 10,
            //         question_list: new Array(1).fill({
            //             question_id: '1',
            //             content: 'afasdf',
            //             options: [
            //                 {
            //                     option_id: 'A',
            //                     options_content: '1'
            //                 },
            //                 {
            //                     option_id: 'B',
            //                     options_content: '2'
            //                 },
            //                 {
            //                     option_id: 'C',
            //                     options_content: '3'
            //                 },
            //                 {
            //                     option_id: 'd',
            //                     options_content: '4'
            //                 }
            //             ]
            //         })
            //     },
            //     {
            //         question_type: '简答题',
            //         score: 10,
            //         question_list: new Array(1).fill({
            //             question_id: '1',
            //             content: 'afasdf'
            //         })
            //     }
            // ]
            // data.forEach(item => {
            //     typeList[item.question_type] = {
            //         score: item.score,
            //         num: item.question_list.length
            //     };
            //     this.pageArr.push(item.question_type);
            //     this.total += item.score;
            //     questions[item.question_type] = item.question_list;
            //     btnArr[item.question_type] = new Array(Math.floor(item.question_list.length / 31 + 1)).fill(0);
            //     answerArr[item.question_type] = new Array(item.question_list.length).fill(0);
            // });
            // this.setState({
            //     typeList: typeList,
            //     questions: questions,
            //     btnArr: btnArr,
            //     answerArr: answerArr
            // });
        }

        home.getQuestion({
            subject_id: this.params.subject_id
        }).then((data) => {
            const typeList = {};
            const questions = {};
            const btnArr = {};
            const answerArr = {};
            data.forEach(item => {
                typeList[item.question_type] = {
                    score: item.score,
                    num: item.question_list.length
                };
                this.total += item.score;
                this.pageArr.push(item.question_type);
                questions[item.question_type] = item.question_list;
                btnArr[item.question_type] = new Array(Math.floor(item.question_list.length / 31 + 1)).fill(0);
                answerArr[item.question_type] = new Array(item.question_list.length).fill(0);
            });
            this.setState({
                typeList: typeList,
                questions: questions,
                btnArr: btnArr,
                answerArr: answerArr
            });
        }).catch(() => {
            this.setTip('网络错误,获取试卷失败');
        });

    }

    setTip = (info) => this.setState({
        showTip: true,
        tipInfo: info
    }, () => setTimeout(
        () => this.setState({
            showTip: false,
            tipInfo: ''
        }), 1500))

    setConfirm = (info, msg, cb) => {
        const res = { showConfirm: true };
        res.confirmInfo = info;
        res.confirmMsg = msg;
        this.getAnswerSheet();
        res.confirmCallback = cb;
        this.setState(res);
    }

    componentDidMount() {
        if (this.params.subject_id !== undefined) {
            this.getData();
        }
        //this.getData();
        window.onbeforeunload = (e) => {
            if (this.state.submit) {
                return false;
            }
            this.setConfirm(['继续答题', '确定'], '关闭窗口视为主动提交当前考卷', [
                () => this.setState({ showConfirm: false }),
                this.submitPaperCallBack]);
            e.preventDefault();
            return false;
        }
    }

    submitPaperCallBack = () => home.addPaper({
        stu_id: this.params.stu_id,
        paper_start: this.getCurrentTime(),
        answer_sheets: this.getAnswerSheet()
        // eslint-disable-next-line no-console
    }).finally(() => { this.setSubmit(true), this.timer.clearTimer() })

    getCurrentTime = () => {
        const time = new Date();
        const nowTime = time.getFullYear() + "-" + time.getMonth() + "-" + time.getDate() + " " + time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();
        return nowTime;
    }

    componentWillUnmount() {
        window.onbeforeunload = null;
    }

    setAnswerArr = (type, value, index) => {
        this.setState((pre) => {
            const res = {};
            res.answerArr = Object.assign(pre.answerArr);
            res.answerArr[type][index] = value;
            return res;
        })
    }

    setBtnArr = (type, current) => {
        this.setState((pre) => {
            const index = Math.floor(current / 31);
            const id = current % 31;
            const res = {};
            res.btnArr = Object.assign(pre.btnArr);
            res.btnArr[type][index] = (pre.btnArr[type][index] | (1 << id));
            return res;
        })
    }

    setPage = (value) => {
        this.setState({ pageNum: value })
    }

    setSubmit = (value) => {
        this.setState({ submit: value, showConfirm: false })
    }

    getAnswerSheet = () => {
        const { answerArr, questions } = this.state;
        const answer_sheets = [];
        Object.keys(answerArr).forEach(type => {
            const answers = answerArr[type];
            const sheet = answers.map((item, index) => {
                let answer = '';
                if (type !== '简答题') {
                    for (let i = 0; i < 4; i++) {
                        if ((item & (1 << i)) >> i === 1) {
                            answer += String.fromCharCode(65 + i);
                        }
                    }
                    return {
                        question_id: questions[type][index].question_id,
                        question_answer: answer,
                    }
                } else return {
                    question_id: questions[type][index].question_id,
                    question_answer: item,
                    //question_content: questions[type][index].question_content
                };
            });
            answer_sheets.push({
                question_type: type,
                sheet: sheet
            });
        });
        return answer_sheets;
    }

    timeOut = () => {
        home.addPaper({
            stu_id: this.params.stu_id,
            paper_start: this.start_time,
            answer_sheets: this.getAnswerSheet()
            // eslint-disable-next-line no-console
        }).then(
            () => {
                this.setSubmit(true);
                const res = { showConfirm: true };
                res.confirmInfo = '我知道了';
                res.confirmMsg = '您的答题时间已到，系统已自动提交，本次考试结束';
                res.confirmCallback = () => {
                    this.setSubmit(true);
                    this.setState({ showConfirm: false })
                    // eslint-disable-next-line no-console
                };
                this.setState(res);;
                // eslint-disable-next-line no-console
            }).catch(() => this.setTip('网络错误'));
    }

    checkPaper = () => {
        let fristPage = -1, fristEmpty = -1, emptyNum = 0;
        const answerArr = this.state.answerArr;
        Object.keys(answerArr).forEach((index) => {
            const item = answerArr[index];
            for (let j = 0, len = item.length; j < len; j++) {
                if (item[j] === 0 || item[j] === '') {
                    if (fristPage === -1) {
                        fristPage = index;
                        fristEmpty = j;
                    }
                    // eslint-disable-next-line no-plusplus
                    emptyNum++;
                }
            }
        });
        const res = { showConfirm: true };
        if (emptyNum === 0) {
            this.setConfirm(['取消', '确定'], '提交试卷后不可再进行修改确认提交？', [
                () => this.setState({ showConfirm: false }),
                this.submitPaperCallBack
            ]);
        } else {
            this.setConfirm(['去答题', '确定'], '您还有' + emptyNum + '题未作答，确认提交？', [
                () => this.setState({
                    showConfirm: false,
                    pageNum: this.pageArr.findIndex(item => item === fristPage)
                }, () => this.test.setCurrent('next-empty', fristEmpty)),
                this.submitPaperCallBack
            ]);
        }
        this.setState(res);
    }

    render() {
        return this.params.subject_id === undefined ? null : (
            <div>
                <Header></Header>
                <div className="page-main-content-box">
                    {
                        this.state.submit ? <Finish></Finish>
                            : (
                                <div>
                                    <Time
                                        changeSubmit={this.checkPaper}
                                        timeOut={this.timeOut}
                                        setTip={this.setTip}
                                        testInfo={this.params}
                                        onRef={ref => this.timer = ref}
                                    ></Time>
                                    <div className="page-main-content-dash dash"></div>
                                    {
                                        this.pageArr[this.state.pageNum] === '首页' ? (
                                            <div>
                                                <Title total={this.total}></Title>
                                                <List
                                                    pageArr={this.pageArr}
                                                    typeList={this.state.typeList}
                                                    changePage={this.setPage}
                                                >
                                                </List>
                                            </div>
                                        )
                                            :
                                            <Test
                                                changePage={this.setPage}
                                                typeInfo={this.state.typeList[this.pageArr[this.state.pageNum]]}
                                                type={this.pageArr[this.state.pageNum]}
                                                currentPage={this.state.pageNum}
                                                changeBtnArr={this.setBtnArr}
                                                btn={this.state.btnArr[this.pageArr[this.state.pageNum]]}
                                                changeAnswerArr={this.setAnswerArr}
                                                answer={this.state.answerArr[this.pageArr[this.state.pageNum]]}
                                                len={this.state.typeList[this.pageArr[this.state.pageNum]].num}
                                                lastPage={this.pageArr[this.pageArr.length - 1]}
                                                onRef={(ref) => this.test = ref}
                                                questions={this.state.questions[this.pageArr[this.state.pageNum]]}
                                                setTip={this.setTip}
                                            >
                                            </Test>
                                    }
                                </div>
                            )
                    }
                    {
                        this.state.showTip
                            ?
                            <Tip
                                info={this.state.tipInfo}
                            ></Tip> : null
                    }
                </div>
                {
                    this.state.showConfirm ?
                        <Confirm
                            msg={this.state.confirmMsg}
                            callBack={this.state.confirmCallback}
                            info={this.state.confirmInfo}
                        ></Confirm>
                        : null
                }
            </div>
        )
    }
}